package cn.edu.java.io.outputstream;

import lombok.SneakyThrows;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {
    @SneakyThrows
    public static void main(String[] args) {
        // 创建一个RandomAccessFile对象，以读写方式打开文件
        RandomAccessFile file = new RandomAccessFile("output/example.txt", "rw");

        // 获取文件的FileChannel
        FileChannel channel = file.getChannel();

        // 创建一个ByteBuffer来存储数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 向ByteBuffer中写入数据
        String data = "Hello, FileChannel!";
        buffer.put(data.getBytes());
        buffer.flip(); // 切换为读模式

        // 将数据从ByteBuffer写入到FileChannel
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }

        // 清空ByteBuffer，准备读取数据
        buffer.clear();

        // 从FileChannel读取数据到ByteBuffer
        while (channel.read(buffer) != -1) {
            buffer.flip(); // 切换为读模式

            // 从ByteBuffer中读取数据并打印
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }

            buffer.clear(); // 清空ByteBuffer，准备下一次读取
        }

        // 关闭FileChannel和RandomAccessFile
        channel.close();
        file.close();
    }
}

